package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.utils.CurrentUserContextHolders;
import com.qk.domain.clue.ClueSelectPoolByPageDO;
import com.qk.dto.clue.ClueDTO;
import com.qk.dto.clue.ClueSelectPoolByPageDTO;
import com.qk.dto.clue.ClueToFalsyDTO;
import com.qk.dto.clue.ClueUpdateDTO;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordsMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.domain.clue.ClueDO;
import com.qk.vo.clue.ClueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/*
 *  @author SHCJ
 *  @created 2025/10/13 20:30
 *  @description
 */
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService{
    @Autowired
    private ClueTrackRecordsMapper clueTrackRecordsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BusinessMapper businessMapper;
    @Override
    public void addClue(ClueDTO clueDTO) {
//        参数校验
        if(clueDTO.getPhone()==null||clueDTO.getChannel()== null){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

//        获取参数clue
        Clue clue = BeanUtil.copyProperties(clueDTO, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.save(clue);
    }

    @Override
    public PageResult<ClueDO> selectByPage(ClueDTO clueDTO) {
        PageHelper.startPage(clueDTO.getPage(),clueDTO.getPageSize());
//        this.baseMapper.selectByPage(clueDTO);
        PageInfo<ClueDO> pageInfo = new PageInfo<>(this.baseMapper.selectByPage(clueDTO));
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public void updateClueById(Integer clueId, Integer userId) {
        this.baseMapper.updateById(Clue.builder()
                .id(clueId)
                .userId(userId)
                .status(ClueStatusConstants.WAIT_FOLLOW_UP)
                .updateTime(LocalDateTime.now())
                .build());

    }

    @Override
    public ClueVO selectClueById(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        User user = userMapper.selectById(clue.getUserId());
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordsMapper.selectList(Wrappers
                .<ClueTrackRecord>lambdaQuery()
                .in(ClueTrackRecord::getClueId, id));
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordsVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordsVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordsVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        // 设置跟进记录
        clueVO.setTrackRecords( list);
        return clueVO;
    }

//    事务处理
    @Transactional
    @Override
    public void updateClue(ClueUpdateDTO clueUpdateDTO) {
        Clue clue = BeanUtil.copyProperties(clueUpdateDTO, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.FOLLOWING);

        this.updateById(clue);
        clueTrackRecordsMapper.insert(ClueTrackRecord.builder()
                .clueId(clueUpdateDTO.getId())
                .subject(clueUpdateDTO.getSubject())
                .record(clueUpdateDTO.getRecord())
                .userId(CurrentUserContextHolders.get())
                .level(clueUpdateDTO.getLevel())
                .type(1)
                .nextTime(clueUpdateDTO.getNextTime())
                .createTime(LocalDateTime.now())
                .build());
    }

    @Override
    public void clueToBusiness(Integer id) {

        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);


        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId( null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        this.businessMapper.insert(business);
    }

    @Override
    public void toFalseClue(Integer id, ClueToFalsyDTO clueToFalsyDTO) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.FALSY);
        this.baseMapper.updateById(clue);

        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(clue, ClueTrackRecord.class);
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(id);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        clueTrackRecord.setType(0);
        clueTrackRecord.setFalseReason(clueToFalsyDTO.getReason());
        if (clueToFalsyDTO.getRemark() != null)
            clueTrackRecord.setRecord(clueToFalsyDTO.getRemark());

        this.clueTrackRecordsMapper.insert(clueTrackRecord);
    }

    @Override
    public PageResult<ClueSelectPoolByPageDO> selectPoolByPage(ClueSelectPoolByPageDTO clueDTO) {
        PageHelper.startPage(clueDTO.getPage(),clueDTO.getPageSize());
        PageInfo<ClueSelectPoolByPageDO> pageInfo = new PageInfo<>(this.baseMapper.selectPoolByPage(clueDTO));
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }
}
